﻿using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using ShenNius.Caches;
using ShenNius.Sys.API.Infrastructure.Common;
using System;
using System.Text;
using System.Threading.Tasks;

namespace ShenNius.Sys.API.Domain.ValueObjects
{
    public class SysSetting
    {

        public string Name { get; set; }
        public string EnName { get; set; }
        public string Logo { get; set; }
        public string Copyright { get; set; }
        public string LoginImg { get; set; }
        public string Favicon { get; set; }
        public string Remark { get; set; }
        public static Task WriteAsync(SysSetting input)
        {
            if (input == null)
            {
                throw new ArgumentNullException(nameof(input));
            }
            var _cacheHelper = MyHttpContext.Current.RequestServices.GetRequiredService<IDistributedCache>();
            var setting = JsonConvert.SerializeObject(input);
            _cacheHelper.Set(nameof(ConfigType.Setting), input);
            return System.IO.File.WriteAllTextAsync(@"wwwroot/system.ini", setting, Encoding.UTF8);

        }
        public static async Task<SysSetting> ReadAsync()
        {
            var _cacheHelper = MyHttpContext.Current.RequestServices.GetRequiredService<IDistributedCache>();
            var value = _cacheHelper.Get<SysSetting>(nameof(ConfigType.Setting));
            if (value == null)
            {
                var valueStr = await System.IO.File.ReadAllTextAsync(@"wwwroot/system.ini", Encoding.UTF8);
                if (!string.IsNullOrEmpty(valueStr))
                {
                    value = JsonConvert.DeserializeObject<SysSetting>(valueStr);
                    _cacheHelper.Set(nameof(ConfigType.Setting), value);
                }
                else
                {
                    value = new SysSetting();
                }
            }
            return value;
        }
    }
}
